package com.example.wyh.bluetoothpro;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {


    final String Name = "Blue";

    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private LinkedList<BluetoothDevice> dataList;

    private BluetoothAdapter bluetoothAdapter;

    private BlueAdapter blueAdapter;


    private ConnectedThread connectedThread;

    private ListView listView;

    private Button searchBtn;

    private Button writeBtn;

    public static BluetoothSocket mBluetoothSocket;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    Log.e("device", device.getName() + device.getAddress());
                    dataList.add(device);
                    blueAdapter = new BlueAdapter(dataList, MainActivity.this);
                    listView.setAdapter(blueAdapter);

                }
            } else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                setProgressBarIndeterminateVisibility(true);
                Toast.makeText(MainActivity.this, "搜索完成", Toast.LENGTH_SHORT).show();
                setTitle("Bluetooth");
            }
        }
    };

    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;
            try {
                tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(Name, uuid);
            } catch (IOException e) {}
            mmServerSocket = tmp;
        }

        public void run() {
            BluetoothSocket socket = null;
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    break;
                }

                if (socket != null) {
                    cancel();
                    break;

                }
            }
        }

        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) {}
        }
    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;
            try {
                tmp = device.createRfcommSocketToServiceRecord(uuid);
                mBluetoothSocket = tmp;
            } catch(IOException e) {
                Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }
            mmSocket = tmp;
        }

        public void run() {
            bluetoothAdapter.cancelDiscovery();

            try {
                mmSocket.connect();
            } catch(IOException connectException) {
                try {
                    System.out.println(connectException);
//                    Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    Log.e("失败", "失败");
                    mmSocket.close();
                } catch (IOException closeException) {
                    Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                }

                return;
            }

            Log.e("chenggong", "chenggong");
            connectedThread = new ConnectedThread(mmSocket);
            connectedThread.start();

            writeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("write abc");
                    connectedThread.write("abc".getBytes());
                }
            });

            //Connect
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch(IOException e) {
                Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {}

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;

            while(true) {
                System.out.println("ConnectedThread run");
                try {
                    bytes = mmInStream.read(buffer);
                    System.out.println("readMessage is :" + bytes);
                } catch (IOException e) {
                    break;
                }
            }
        }

        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {}
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {}
        }

    }


    private void initData() {
        dataList = new LinkedList<>();

        searchBtn = (Button)findViewById(R.id.search);

        listView = (ListView)findViewById(R.id.list_bluetooth);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        writeBtn = (Button)findViewById(R.id.write);
    }


    private void bluetoothIsEnabled() {
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "本地蓝牙不可用", Toast.LENGTH_SHORT).show();
            finish();
        }

        Toast.makeText(this, "本地蓝牙可用", Toast.LENGTH_SHORT).show();

        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, );
        }
    }



    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();

        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);

        bluetoothIsEnabled();

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                dataList.clear();
//                setProgressBarIndeterminateVisibility(true);
//                if (bluetoothAdapter.isDiscovering()) {
//                    bluetoothAdapter.cancelDiscovery();
//                }
//                setTitle("正在扫描...");
//
//                bluetoothAdapter.startDiscovery();

                Intent intent = new Intent();
                intent.setClass(MainActivity.this, BlueMain.class);
                startActivity(intent);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice service = dataList.get(position);
                System.out.println("UUID" + service);
//                getRemoteDevice(service);
                ConnectThread connectThread = new ConnectThread(service);
                connectThread.start();
            }
        });

        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        ArrayList array = new ArrayList();
        for (BluetoothDevice device: pairedDevices) {
            array.add(device.getName() + "\t" + device.getUuids());
        }
        System.out.println(array);

        AcceptThread acceptThread = new AcceptThread();
        acceptThread.start();

        registerReceiver();


    }



}
